package xyz.naokeziteng.leetcode;

/**
 * 414题：第三大的数字
 */
public class ThirdNumber {

    public static int thirdMax(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums.length == 2) {
            return Math.max(nums[0], nums[1]);
        }
        int first;
        int second;
        int third;
        boolean hasSecond = false;
        boolean hasThird = false;

        //找出最大值
        first = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > first) {
                first = nums[i];
            }
        }
        //找出第二大值
        second = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < first && nums[i] >= second) {
                second = nums[i];
                hasSecond = true;
            }
        }
        if (!hasSecond) {
            return first;
        }
        //找出第三大值
        third = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < second && nums[i] >= third) {
                third = nums[i];
                hasThird = true;
            }
        }


        return hasThird ? third : first;
    }

    public static void main(String[] args) {
        int[] nums = {1, -2147483648, 2};
        System.out.println(thirdMax(nums));
    }
}
